package cn.phonevane.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import cn.phonevane.base.BaseAction;
import cn.phonevane.model.PageModel;
import cn.phonevane.model.TArticle;
import cn.phonevane.model.TArticleFile;
import cn.phonevane.service.ArticleFileService;
import cn.phonevane.service.ArticleService;
import cn.phonevane.utils.CheckFileType;
import cn.phonevane.utils.PagingModule;
import cn.phonevane.utils.SystemConstant;

public class ArticleAction extends BaseAction{
	
	
	
	
	//上传文件域对象
	private File[] uploads;
	//上传文件名
	private String[] uploadFileNames;
	//上传文件类型
	private String[] uploadContentTypes;
	//上传文件保存路径（通过sturts配置文件注入）
	private String savePath;
	//上传图片保存路径（通过struts配置文件注入）
	private String savePicture;
	
	private ArticleService articleService;
	
	private ArticleFileService articleFileServer;
	
	public ArticleService getArticleService() {
		return articleService;
	}


	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}	
	public ArticleFileService getArticleFileServer() {
		return articleFileServer;
	}


	public void setArticleFileServer(ArticleFileService articleFileServer) {
		this.articleFileServer = articleFileServer;
	}


	public File[] getUpload() {
		
		return this.uploads;
	} 
	public void setUpload(File[] upload) {
		this.uploads = upload; 
	} 
	 
	public String[] getUploadFileName() { 
		return this.uploadFileNames;
	} 
	public void setUploadFileName(String[] uploadFileName) { 
		this.uploadFileNames = uploadFileName; 
	} 
	 
	public String[] getUploadContentType() { 
		return this.uploadContentTypes; 
	} 
	public void setUploadContentType(String[] uploadContentType) { 
		this.uploadContentTypes = uploadContentType; 
	}
	
	public String getSavePath() {
		return savePath;
	}


	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	
	public String getSavePicture() {
		return savePicture;
	}


	public void setSavePicture(String savePicture) {
		this.savePicture = savePicture;
	}
	
	/**
	 * 分页获取文章数据
	 */
	public void list(){
		
		int currentPage=Integer.parseInt(httpServletRequest.getParameter("currentPage"));
		List<TArticle> list=this.articleService.getPart(currentPage,SystemConstant.PAGE_SIZE);
		int count=this.articleService.getCount();
		System.out.println("count="+count);
		int maxPage=PagingModule.maxPageSize(count);
		PageModel<TArticle> pm=new PageModel<TArticle>(list,maxPage);
		httpServletRequest.setAttribute("pm", pm);
		
		
		
	}
	


	/**
	 * 把源文件对象复制成目标文件对象
	 */
	private static void copy(File src,File dst){
		InputStream in=null;
		OutputStream out=null;
		try{
		in=new BufferedInputStream(new FileInputStream(src),SystemConstant.BUFFER_SIZE); 
		out=new BufferedOutputStream(new FileOutputStream(dst),SystemConstant.BUFFER_SIZE);
		byte[] buffer= new byte[SystemConstant.BUFFER_SIZE];
		int len=0;
		while((len=in.read(buffer))>0){
			out.write(buffer, 0, len);
		}
		}catch(Exception e){
			logger.info("upload failed!",e);
		}finally{
			if(in!=null){
				try{
				in.close();
				in=null;
				}catch(IOException e){
					logger.info("in close failed!",e);
				}
			}
			if(out!=null){
				try{
				out.close();
				out=null;
				}catch(IOException e){
					logger.info("out close failed!",e);
				}
			}
		}
	}


	/**
	 * 添加文章数据
	 * 
	 * @param title,color,keywords,source,username,grade,show,haspic,consult,typeid,content
	 */
	public String issue(){
		
		String title=(String)httpServletRequest.getParameter("title");
		int color=Integer.parseInt(httpServletRequest.getParameter("color"));
		String keywords=(String)httpServletRequest.getParameter("keywords");
		String source=(String)httpServletRequest.getParameter("source");
		String username=(String)httpServletRequest.getParameter("username");
		int grade=Integer.parseInt(httpServletRequest.getParameter("grade"));
		int show=Integer.parseInt(httpServletRequest.getParameter("show"));
		int ifauthority=Integer.parseInt(httpServletRequest.getParameter("ifauthority"));
		int consult=Integer.parseInt(httpServletRequest.getParameter("consult"));
		int typeid=Integer.parseInt(httpServletRequest.getParameter("typeid"));
		String content=(String)httpServletRequest.getParameter("content");
		
		File[] srcFiles = this.getUpload();
		String aFileIndex="0";
		if(srcFiles!=null){
			SimpleDateFormat sf=new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName=null,dstPath=null,newFileUrl=null,fileType=null,times=null;
			times=sf.format(new Date());
			aFileIndex=CheckFileType.createString()+times;
			// 处理每个要上传的文件
	        for (int i = 0; i < srcFiles.length; i++) {
	        	TArticleFile aFile=new TArticleFile();
	        	newFileName=times+i+CheckFileType.getExtention(this.getUploadFileName()[i]);
	        	fileType=this.getUploadContentType()[i];
	        	
	        	//判断是否为图片文件
	        	if(CheckFileType.isPic(this.getUploadFileName()[i])){
	        		 // 根据服务器的文件保存地址和文件名创建目录文件全路径
	        	    dstPath=ServletActionContext.getServletContext()
	        		.getRealPath(this.getSavePicture())
	        		+"/"+newFileName;	
	        	    newFileUrl=this.savePicture+"/"+newFileName;
	        	    
	        	}else{
	        		 // 根据服务器的文件保存地址和原文件名创建目录文件全路径
	                dstPath = ServletActionContext.getServletContext()
	                        .getRealPath(this.getSavePath())
	                        + "/" +newFileName;
	                newFileUrl=this.savePath+"/"+newFileName;
	                
	        	}
	        	
	        	aFile.setArticleFileIndex(aFileIndex);
	        	aFile.setArticleFileType(fileType);
	        	aFile.setArticleFileName(newFileName);
	        	aFile.setArticleFileUrl(newFileUrl);
	        	aFile.setArticleFileDown(dstPath);
	        	
	        	File dstFile= new File(dstPath);
	    		this.copy(srcFiles[i], dstFile); 
	    		this.articleFileServer.add(aFile);
	        }
		}
        

		if(!title.equals("")&&!username.equals("")){
			TArticle tArticle=new TArticle();//创建文章数据对象
			tArticle.setArticleTitle(title);//设置文章标题
			tArticle.setArticleColor(color);//设置文章标题颜色：0为黑色，1为红色，2为绿色，3，蓝色
			tArticle.setArticleKeywords(keywords);//设置文章关键字
			tArticle.setArticleSource(source);//设置文章来源
			tArticle.setUserName(username);//设置作者名
			tArticle.setArticleCreateTime(new Date());//设置文章发布时间
			tArticle.setArticleGrade(grade);//设置文章是否在首页显示
			tArticle.setArticleShow(show);//设置文章是否在网站上显示
			tArticle.setArticleIfAuthority(ifauthority);//设置文章是否为官方文章
			tArticle.setArticleConsult(consult);//管理员是否同意这篇文章的申请
			tArticle.setArticleTypeId(typeid);//设置文章类型id
			tArticle.setArticleContent(content);//写入文章内容
			tArticle.setArticleFileIndex(aFileIndex);//写入文章附件索引
			boolean sign=this.articleService.add(tArticle);//保存文章到数据库
			if(sign==true){
				return SUCCESS;
			}
		}
		return ERROR;
	}
	
	
	/**
	 * 根据文章ID查找获取文章
	 */
	public String getArticleById(){
		String str=httpServletRequest.getParameter("articleId");
		Long articleId;
		if(str==null||str.equals("")){
			articleId=1L;
		}else{
			try{
				articleId=Long.parseLong(str.intern());
			}catch(NumberFormatException e){
				articleId=1L;
			}
		}
		if(articleId>0){
			TArticle tArticle=this.articleService.getById(articleId);
			if(tArticle!=null){
				httpServletRequest.setAttribute("TARTICLE",tArticle);
				String aFileIndex=tArticle.getArticleFileIndex();
				if(aFileIndex!=null&&!aFileIndex.equals("0")){
					List<TArticleFile> tArticleFile=this.articleFileServer.getByIndex(aFileIndex);
					httpServletRequest.setAttribute("ARTICLE_FILE", tArticleFile);
				}
				return SUCCESS;
			}
			
		}
		return ERROR;
	}
}
